<template>
  <div v-if="authStore.isAuthenticated" class="user-management-container">
    <h2>User Management</h2>
    <a-alert v-if="error" type="error">{{ error }}</a-alert>
    <a-spin :spinning="loading">
      <a-table :columns="columns" :data-source="users" bordered>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-popconfirm title="Are you sure delete this user?" ok-text="Yes" cancel-text="No"
              @confirm="showConfirm(record.id)" @cancel="cancel">
              <a href="#" style="color: red;">Delete</a>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-spin>
  </div>
  <a-alert v-else class="no-data" type="warning" show-icon>
    <template #message>
      You must log in/register to manage users.
    </template>
    <template #description>
      Redirecting to the login page in {{ countdown }} seconds...
    </template>
  </a-alert>
  <a-modal v-model:visible="confirmVisible" title="Delete Confirmation" ok-text="Confirm Delete" cancel-text="Cancel" @ok="handleDelete">
    <p>Are you sure you want to delete the information of User ID {{ currentUserId }}?</p>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';
import axios from '../axios';
import { message } from 'ant-design-vue';

interface User {
  id: number;
  username: string;
  role: {
    id: number;
    name: string;
  };
}

const authStore = useAuthStore();
const router = useRouter();
const users = ref<User[]>([]);
const loading = ref(false);
const error = ref('');
const countdown = ref(5);
const confirmVisible = ref(false);
const currentUserId = ref(0);

const columns = [
  { title: 'User ID', dataIndex: 'id', key: 'id' },
  { title: 'Username', dataIndex: 'username', key: 'username' },
  { title: 'Role', dataIndex: 'role', key: 'role' },
  { title: 'Actions', key: 'actions' },
];

const cancel = (e: MouseEvent) => {
  console.log(e);
};

const fetchUsers = async () => {
  try {
    loading.value = true;
    const res = await axios.get('/users');
    users.value = res.data.data.map((user: any) => ({
      ...user,
      role: user.role.name // 提取角色名称
    }));
  } catch (err) {
    error.value = 'Failed to obtain user information';
  } finally {
    loading.value = false;
  }
};

const showConfirm = (id: number) => {
  currentUserId.value = id;
  confirmVisible.value = true;
};
const handleDelete = async () => {
  try {
    await axios.delete(`/users/${currentUserId.value}`);
    message.success(`User with ID ${currentUserId.value} deleted successfully.`);
    fetchUsers();
    currentUserId.value = 0;
  } catch (err) {
    console.error(`Failed to delete user with ID ${currentUserId.value}:`, err);
    message.error('Failed to delete user');
  } finally {
    confirmVisible.value = false;
  }
};

onMounted(() => {
  if (authStore.isAuthenticated) {
    fetchUsers();
  }
});
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}
</style>